const router = require("express").Router();
const request = require("request");
const atwork = require("atwork");
const ENV = require("../config/constant").ENV;
const config = require("../config/constant").config;
const apps = require("../config/apps-info");
const parseString = require('xml2js').parseString;

const getCurrentApp = function(req){
	const reqType = req.params.type;
	console.log(reqType);
	const tragetApp = apps.find((item)=>{
		return item.type == reqType;
	});
	// throw new Error();
	return {
		clientId: tragetApp.clientId,
		clientSecret: tragetApp.clientSecret
	}
}

const getAtworkInstance = function(req) {
	// const config = require("../config/constant");
	const atwork = require("atwork");
	const currentApp = getCurrentApp(req);
	// 测试环境org_id 18590d66-26fe-4e78-9344-496370670ccf
	const param = {
		clientId: currentApp.clientId,
		clientSecret: currentApp.clientSecret,
		adminServer: config.apiServer.internal,
		domainId: req.query.domainId || "rfchina",
		orgId: req.query.orgId || "1df94799-fd32-49c3-b6d1-f7c9eb6caf49"
	};
	const instance = atwork(param);
	return instance;
};


const proxyRequest = function(req, params){
	const options = {
		method: "POST",
		url: config.apiServer.internal + "/rf-china/unread/" + params.subscription_id,
		json: true,
		body: {
			"account": params.user_name
		}
	};
	return getAtworkInstance(req).send(options);
};

const getUnreadByType = function(req, res) {
	const subscription_id = (req.query.tabType)?req.query.tabType:req.params.type; //有子项，拿子项type,没有拿params的type

	const params = {
		subscription_id: subscription_id,
		user_name: req.query.user || "maoguodao"
	}
	//console.log(subscription_id);

	if(!req.query.username){//移动端返回username等信息
		res.json({
			"status": 0,
			"tip": {
				"notify_type": "nothing"
			}
		})
	} else {
		if (subscription_id != "processesCenter") {
			proxyRequest(req,params).then(workplusRes=>{
				console.log(workplusRes);
				//res.json(workplusRes);
				if (workplusRes && workplusRes.result > 0) {
					res.json({
						"status": 0,
						"tip": {
							"notify_type": "digit",
							"num": workplusRes.result
						}
					});
				} else {
					res.json({
						"status": 0,
						"tip": {
							"notify_type": "nothing"
						}
					});
				}
			});
		} else {
			//console.log(22222222222);
			const testUrl = "http://bpmuatnew.rfchina.com:99/portal/webservices/rfbpmservice.asmx/GetUserUnfinishedWorkItemCountForAPP";
			const productionUrl = "http://bpm.rfchina.com/portal/webservices/rfbpmservice.asmx/GetUserUnfinishedWorkItemCountForAPP";
			let url = (ENV == "test") ? testUrl : productionUrl;
			request({
				method: "post",
				url: url,
				form: {
					userCode: req.query.username
				}
			}, (e, proxyRes, body) => {
				if (e) {
					console.log(e);
					res.json({
						"status": 0,
						"tip": {
							"notify_type": "nothing"
						}
					});
				} else {
					try{
						parseString(proxyRes.body, function(err, result) {
							console.log(proxyRes.body);
							if ( result && result.int && result.int._ && result.int._ > 0) {
								res.json({
									"status": 0,
									"tip": {
										"notify_type": "digit",
										"num": result.int._
									}
								})
							} else {
								res.json({
									"status": 0,
									"tip": {
										"notify_type": "nothing"
									}
								});
							}
						})
					}catch(error){
						res.json({
								"status": 404
						})
					}
				}
			});
		}
	}
	

	// if(!req.query.username){//移动端返回username等信息
	// 	res.json({
	// 		"status": 0,
	// 		"tip": {
	// 			"notify_type": "nothing"
	// 		}
	// 	})
	// }

	// const testUrl = "http://bpmuatnew.rfchina.com:99/portal/webservices/rfbpmservice.asmx/GetUserUnfinishedWorkItemCountForAPP";
	// const testUrl = "http://puat.rfchina.com/_layouts/15/Custom/WebSerivice/mobilesvc.asmx";
	// const productionUrl = "http://bpm.rfchina.com:99/portal/webservices/rfbpmservice.asmx/GetUserUnfinishedWorkItemCountForAPP";
	// const subscription_id = (req.query.tabType) ? req.query.tabType : req.params.type; //有子项，拿子项type,没有拿params的type
	// let url = (ENV == "test") ? testUrl : productionUrl;
	// request({
	// 	method: "post",
	// 	url: url,
	// 	form: {
	// 		account: req.query.username,
	// 		subscriptionID: subscription_id
	// 	}
	// }, (e, proxyRes, body) => {
	// 	if (e) {
	// 		res.json({
	// 			"status": 0,
	// 			"tip": {
	// 				"notify_type": "nothing"
	// 			}
	// 		});
	// 	} else {
	// 		try{
	// 			parseString(proxyRes.body, function(err, result) {
	// 				console.log(result);
	// 				if ( result && result.int&& result.int._ && result.int._ > 0) {
	// 					res.json({
	// 						"status": 0,
	// 						"tip": {
	// 							"notify_type": "digit",
	// 							"num": result.int._
	// 						}
	// 					})
	// 				}
	// 			})
	// 		}catch(error){
	// 			res.json({
	// 				"status": 404
	// 			})
	// 		}
	// 	}
	// });
}

router.get("/:type", getUnreadByType);
module.exports = router;